//
//  SourceView.m
//  iMiniTao
//
//  Created by liunian on 13-8-14.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "SourceView.h"
#import "GMGridView.h"
#import "GMGridViewLayoutStrategies.h"
#import "RecommendView.h"
#import "MTGridViewCell.h"
#import <QuartzCore/QuartzCore.h>
#import "OptionViewController.h"
#import "MainViewController.h"
#import "SourceViewController.h"
#import "ListViewController.h"
#import "FavoritesController.h"
#import "UIImageView+LBBlurredImage.h"
#import "ApplicationManager.h"
#import "MKNavigationController.h"
#import "WebViewController.h"

#define kTagLogoBGView           1222+0
#define kTagBGMaskView           1222+1

static const int kIntAddSourceStartPostion = 5;

@interface SourceView ()<GMGridViewDataSource,GMGridViewSortingDelegate, GMGridViewDelegate,SourceViewControllerDelegate,SourceManagerDelegate,MKEnvObserverApplicationProtocol>

@property (nonatomic, retain) GMGridView    *gmGridView;
@property (nonatomic, retain) UIPageControl     *pageControl;
@property (nonatomic, assign) BOOL          isIphone5;
@property (nonatomic, assign) NSInteger     emptyCount;
@property (nonatomic, retain) RecommendView  *recommendView;

@property (nonatomic, retain) UIImageView       *topView;
@property (nonatomic, retain) UIButton      *btnFocus;
@property (nonatomic, retain) UIButton      *btnRefresh;
@property (nonatomic, retain) UIButton      *btnOffDown;
@property (nonatomic, retain) UIButton      *btnSetting;
- (void)initSourceView;
- (void)updateTheme;
@end
@implementation SourceView

- (void)dealloc{
    _delegate = nil;
    MKRemoveApplicationObserver(self);
    [[SourceManager sharedManager] removeObserver:self];
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.clipsToBounds = YES;
        self.backgroundColor = [UIColor clearColor];
        self.isIphone5 = frame.size.height > 480;
        self.emptyCount = self.isIphone5?9:6;
        MKAddApplicationObserver(self);
        
        [self initSourceView];
    }
    return self;
}
- (void)initSourceView{
    [self addSubview:self.topView];
    [self.gmGridView.scrollView addSubview:self.recommendView];
    [self addSubview:self.pageControl];
    [[SourceManager sharedManager] addObserver:self];
    [[SourceManager sharedManager] getUserSources];
    
}

- (void)updateTheme{
    [self.gmGridView reloadData];
}
- (void)endEditState
{
    [self.gmGridView setEditing:NO];
    self.isEditing = NO;
}
#pragma mark - 视图出现/离开 相关设置
- (void)sourceViewDidAppear
{
    [DataEnvironment sharedDataEnvironment].numOfDetailView = 0;
    [self.recommendView startAnimation];
    self.isSourceViewShown = YES;
}

- (void)sourceviewWillDisappear
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self.recommendView];
    [self.recommendView stopAnimation];
    self.isSourceViewShown = NO;
    
    if (self.gmGridView.isEditing) {
        [self endEditState];
    }
}

#pragma mark- button action methods
-(void)infoSettingAction:(id)sender
{
    [self endEditState];
    
    if ([_delegate respondsToSelector:@selector(setting)]) {
        [self.delegate setting];
    }
}

- (void)forwardAction:(id)sender
{
    
    [self endEditState];
    
    if ([_delegate respondsToSelector:@selector(forward)]) {
        [self.delegate forward];
    }
}

- (void)searchClick:(id)sender
{
    [DataEnvironment sharedDataEnvironment].isMainViewPresentingController = YES;
    [self endEditState];
    if ([_delegate respondsToSelector:@selector(search)]) {
        [self.delegate search];
    }
}

- (void)favoritClick:(id)sender
{
    
    [self endEditState];
    if ([_delegate respondsToSelector:@selector(favorit)]) {
        [self.delegate favorit];
    }
}

/*
 *根据页码滑动到当前页面所在区域
 */
- (void)scrollRectToVisibleByPage:(int)page
{
    self.currentPage = page;
    [self.gmGridView scrollRectToVisiblePageAtIndex:page animated:YES];
}

- (void)pageValueChange:(id)sender{
    UIPageControl  *contol = (UIPageControl *)sender;
    [self scrollRectToVisibleByPage:contol.currentPage];
}
#pragma mark - 频道处理相关 methods
- (void)addSourceButton:(Source *)source {
    //订阅频道
    MeSource *obj = [[MeSource alloc] initWithSource:source];
    [[SourceManager sharedManager] addSource:obj];
}

- (void)deleteSourceButton:(Source *)source{
    //取消订阅
    MeSource *obj = [[MeSource alloc] initWithSource:source];
    [[SourceManager sharedManager] removeTheMeSource:obj];
}

#pragma mark - SourceViewControllerDelegate
- (void)handleSource:(Source *)source isAdd:(BOOL)isAdd
{
    if (!source)
        return;
    
    if (isAdd) {
        [self addSourceButton:source];
    }else{
        [self deleteSourceButton:source];
    }
}


- (void)handleMeSource:(MeSource *)source isAdd:(BOOL)isAdd{
    if (!source)
        return;
    
    if (isAdd) {
        //订阅频道
        [[SourceManager sharedManager] addSource:source];
    }else{
        //取消订阅
        [[SourceManager sharedManager] removeTheMeSource:source];
    }
}
#pragma mark SourceManagerDelegate
- (void)mkManagerMeSourcesDidFinishedWithSources:(NSMutableArray *)meSources{
    [self updateTheme];
}

- (void)mkModelManagerSubscribeSourcesAtIndex:(NSNumber *)index
{
    NSInteger   insertIndex = [index integerValue]<kIntAddSourceStartPostion?[index integerValue]+self.emptyCount:[index integerValue]+self.emptyCount+1;
    [self.gmGridView insertObjectAtIndex:insertIndex];
    [self.gmGridView reloadObjectAtIndex:insertIndex];
}

- (void)mkModelManagerUnsubscribeSourcesAtIndex:(NSNumber *)index
{
    NSInteger   delIndex = [index integerValue]<kIntAddSourceStartPostion?[index integerValue]+self.emptyCount:[index integerValue]+self.emptyCount+1;
    [self.gmGridView removeObjectAtIndex:delIndex];
}

#pragma mark GMGridViewDataSource
- (NSInteger)numberOfItemsInGMGridView:(GMGridView *)gridView{
    return [[SourceManager sharedManager].meSources count]+self.emptyCount+1;
}

- (CGSize)sizeForItemsInGMGridView:(GMGridView *)gridView
{
    return CGSizeMake(100.0f, 95.0f);
}

- (GMGridViewCell *)gmGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index{
    if (index<=self.emptyCount-1){
        return nil;
    }
    CGSize size = [self sizeForItemsInGMGridView:gridView];
    MTGridViewCell *cell = (MTGridViewCell *)[gridView dequeueReusableCell];
    
    if (!cell) {
        cell = [[MTGridViewCell alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    }
    NSMutableArray *userSources = [SourceManager sharedManager].meSources;
    if ([userSources count] >= kIntAddSourceStartPostion) {
        if (index-self.emptyCount <kIntAddSourceStartPostion) {
            cell.source = [userSources objectAtIndex:index-self.emptyCount];
        }else if (index-self.emptyCount == kIntAddSourceStartPostion){
            cell.source = nil;
        }else if (index-self.emptyCount > kIntAddSourceStartPostion){
            cell.source = [userSources objectAtIndex:index-self.emptyCount-1];
        }
    }else{
        if (index-self.emptyCount == [userSources count]) {
            cell.source = nil;
        }else if (index-self.emptyCount < [userSources count]) {
            cell.source = [userSources objectAtIndex:index-self.emptyCount];
        }
    }
    
    return cell;
}

- (void)gmGridView:(GMGridView *)gridView deleteItemAtIndex:(NSInteger)index{
    NSInteger  deleteIndex = (index <self.emptyCount+kIntAddSourceStartPostion)?index-self.emptyCount:index-self.emptyCount-1;
    if (deleteIndex>=0 && deleteIndex < [[SourceManager sharedManager].meSources count]) {
        MeSource *source = [[SourceManager sharedManager].meSources objectAtIndex:deleteIndex];
        [[SourceManager sharedManager] removeMeSource:source];
    }
}

#pragma mark - GMGridViewDelegate
- (void)gmGridViewDidEndEditing:(GMGridView *)gridView{
    self.isEditing = NO;
}

- (void)gmGridView:(GMGridView *)gridView pageNumberInGridView:(NSInteger)pageNumber{
    
    NSInteger  countPerPage = self.isIphone5?15:12;
    // 重新计算page数
    _totalPage = ceil(([[SourceManager sharedManager].meSources count]+self.emptyCount+1)*1.0/countPerPage);
    self.pageControl.numberOfPages = _totalPage;
    self.currentPage = pageNumber;
}

- (void)gmGridView:(GMGridView *)gridView didSelectItemAtIndex:(NSInteger)index
{
    if (!self.isSourceViewShown){
        return;
    }
    if (self.gmGridView.isEditing) {
        [self endEditState];
        return;
    }
    
    MTGridViewCell  *cell = (MTGridViewCell  *)[gridView cellForItemAtIndex:index];
    if (cell.source == nil)
    {
        
        [DataEnvironment sharedDataEnvironment].isMainViewPresentingController = YES;
        SourceViewController  *sourceVC = [[SourceViewController alloc] init];
        sourceVC.delegate = self;
        MKNavigationController *nav = [[MKNavigationController alloc] initWithRootViewController:sourceVC];
        [[[DataEnvironment sharedDataEnvironment] navController] presentViewController:nav animated:YES completion:nil];
        return;
    }
    BMLog(@"itemtype:%d",cell.source.itemtype);
    if (cell.source.itemtype == ITEMTYPECUZYITEM || cell.source.itemtype == ITEMTYPEKEYWORD) {
        ListViewController *listVC = [[ListViewController alloc] initWithMeSource:cell.source];
        [[[DataEnvironment sharedDataEnvironment] navController] pushViewController:listVC animated:YES];
        RELEASE_SAFELY(listVC);
    }else if (cell.source.itemtype == ITEMTYPESHOP){
        
    }else if (cell.source.itemtype == ITEMTYPEGROUP){
        
    }else if (cell.source.itemtype == ITEMTYPEWAP){
        WebViewController *webVC = [[WebViewController alloc] initWithURL:[NSURL URLWithString:cell.source.url]];
        [[[DataEnvironment sharedDataEnvironment] navController] pushViewController:webVC animated:YES];
        RELEASE_SAFELY(webVC);
    }
}



#pragma mark - GMGridViewSortingDelegate
- (void)gmGridView:(GMGridView *)gridView didStartMovingCell:(GMGridViewCell *)cell
{
    self.isEditing = YES;
    
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         cell.deleteButton.alpha = 1.0;
                         cell.layer.transform = CATransform3DMakeScale(1.04, 1.04, 1.0);
                         cell.contentView.layer.shadowOpacity = 0.7;
                     }
                     completion:nil
     ];
}

- (void)gmGridView:(GMGridView *)gridView didEndMovingCell:(GMGridViewCell *)cell
{
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         cell.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.9);
                         cell.contentView.layer.shadowOpacity = 0;
                     }
                     completion:nil
     ];
}

- (void)gmGridView:(GMGridView *)gridView moveItemAtIndex:(NSInteger)oldIndex toIndex:(NSInteger)newIndex{
    BMLog(@"[oldIndex:%d  , newIndex:%d]",oldIndex,newIndex);
    NSInteger index1 = (oldIndex <self.emptyCount+kIntAddSourceStartPostion)?oldIndex-self.emptyCount:oldIndex-self.emptyCount-1;
    NSInteger index2 = (newIndex <self.emptyCount+kIntAddSourceStartPostion)?newIndex-self.emptyCount:newIndex-self.emptyCount-1;
    MeSource *object1 = [[SourceManager sharedManager].meSources objectAtIndex:index1];
    
    [[SourceManager sharedManager].meSources removeObject:object1];
    
    [[SourceManager sharedManager].meSources insertObject:object1
                                                  atIndex:index2];
    [[SourceManager sharedManager] reorderMeSources];
}

#pragma mark - 监听程序进入后台
- (void)mkEnvObserverApplicationDidEnterBackground:(NSNotification *)notification{
    //如果为编辑状态，则结束编辑态
    if (self.isEditing) {
        [self endEditState];
    }
}
- (void)mkEnvObserverApplicationWillEnterForeground:(NSNotification *)notification{
}

#pragma mark getter

- (GMGridView *)gmGridView{
    if (!_gmGridView) {
        NSInteger spacing = 0;
        _gmGridView = [[GMGridView alloc] initWithFrame:CGRectMake(0, 42, self.bounds.size.width, self.pageControl.frame.origin.y-38)];
        _gmGridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _gmGridView.backgroundColor = [UIColor clearColor];

        _gmGridView.itemHorizontalSpacing = self.isIphone5?5:5;
        _gmGridView.itemVerticalSpacing = self.isIphone5?3:5;
        
        _gmGridView.minEdgeInsets = UIEdgeInsetsMake(spacing, spacing, spacing, spacing);
        _gmGridView.centerGrid = YES;
        _gmGridView.actionDelegate = self;
        _gmGridView.sortingDelegate = self;
        _gmGridView.dataSource = self;
        _gmGridView.isDestop = YES;
        _gmGridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutHorizontalPagedLTR];
        [self addSubview:_gmGridView];
    }
    return _gmGridView;
}

- (RecommendView *)recommendView{
    if (!_recommendView) {
        CGFloat  height = self.isIphone5?291:196;
        _recommendView = [[RecommendView alloc] initWithFrame:CGRectMake(5, 2, 310, height)];
    }
    return _recommendView;
}
- (UIImageView *)topView{
    if (!_topView) {
        _topView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        _topView.backgroundColor = [UIColor clearColor];
        _topView.userInteractionEnabled = YES;
        

        
        UIImage *imgSet = IMGFROMBUNDLE(@"button_setting_normal.png");
        UIImage  *imgSet_h = IMGFROMBUNDLE(@"button_setting_pressed.png");
        self.btnSetting.frame = CGRectMake(5, floorf((_topView.bounds.size.height-imgSet.size.height)/2), imgSet.size.width, imgSet.size.height);
        [self.btnSetting setImage:imgSet forState:UIControlStateNormal];
        [self.btnSetting setImage:imgSet_h forState:UIControlStateHighlighted];
        [_topView addSubview:self.btnSetting];
        
        UIImage *imgSearch = IMGFROMBUNDLE(@"button_storesearch_normal.png");
        UIImage  *imgSearch_h = IMGFROMBUNDLE(@"button_storesearch_pressed.png");
        self.btnOffDown.frame = CGRectMake(self.btnSetting.frame.origin.x+imgSet.size.width+5, floorf((_topView.bounds.size.height-imgSearch.size.height)/2), imgSearch.size.width, imgSearch.size.height);
        [self.btnOffDown setImage:imgSearch forState:UIControlStateNormal];
        [self.btnOffDown setImage:imgSearch_h forState:UIControlStateHighlighted];
        [_topView addSubview:self.btnOffDown];
        

        
        UIImage  *imgFocus = IMGFROMBUNDLE(@"button_shoppingcar.png");
        UIImage  *imgFocus_h = IMGFROMBUNDLE(@"button_shoppingcar_pressed.png");
        self.btnFocus.frame = CGRectMake(self.btnOffDown.frame.origin.x+imgFocus.size.width+5, floorf((_topView.bounds.size.height-imgFocus.size.height)/2), imgFocus.size.width, imgFocus.size.height);
        [self.btnFocus setImage:imgFocus forState:UIControlStateNormal];
        [self.btnFocus setImage:imgFocus_h forState:UIControlStateHighlighted];
        [_topView addSubview:self.btnFocus];
        
        UIImage *imgRefresh = IMGFROMBUNDLE(@"button_share_normal.png");
        UIImage *imgRefresh_h = IMGFROMBUNDLE(@"button_share_pressed.png");
        self.btnRefresh.frame = CGRectMake(self.btnFocus.frame.origin.x+imgFocus.size.width+5, floorf((_topView.bounds.size.height-imgRefresh.size.height)/2), imgRefresh.size.width, imgRefresh.size.height);
        [self.btnRefresh setImage:imgRefresh forState:UIControlStateNormal];
        [self.btnRefresh setImage:imgRefresh_h forState:UIControlStateHighlighted];
        [_topView addSubview:self.btnRefresh];
    }
    return _topView;
}

- (UIButton *)btnRefresh{
    if (!_btnRefresh) {
        _btnRefresh = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnRefresh.backgroundColor = [UIColor clearColor];
        _btnRefresh.autoresizingMask = UIViewContentModeScaleAspectFill;
        _btnRefresh.exclusiveTouch = YES;
        [_btnRefresh addTarget:self
                        action:@selector(forwardAction:)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnRefresh;
}

- (UIButton *)btnFocus{
    if (!_btnFocus) {
        _btnFocus = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnFocus.backgroundColor = [UIColor clearColor];
        _btnFocus.autoresizingMask = UIViewContentModeScaleAspectFill;
        _btnFocus.exclusiveTouch = YES;
        [_btnFocus addTarget:self
                      action:@selector(favoritClick:)
            forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnFocus;
}

- (UIButton *)btnOffDown{
    if (!_btnOffDown) {
        _btnOffDown = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnOffDown.backgroundColor = [UIColor clearColor];
        _btnOffDown.autoresizingMask = UIViewContentModeScaleAspectFill;
        _btnOffDown.exclusiveTouch = YES;
        [_btnOffDown addTarget:self
                        action:@selector(searchClick:)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnOffDown;
}

- (UIButton *)btnSetting{
    if (!_btnSetting) {
        _btnSetting = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnSetting.backgroundColor = [UIColor clearColor];
        _btnSetting.autoresizingMask = UIViewContentModeScaleAspectFill;
        _btnSetting.exclusiveTouch = YES;
        [_btnSetting addTarget:self
                        action:@selector(infoSettingAction:)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnSetting;
}

- (UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(140, self.bounds.size.height-16, 40, 16)];
        _pageControl.backgroundColor = [UIColor clearColor];
        [_pageControl addTarget:self
                         action:@selector(pageValueChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _pageControl;
}
#pragma mark - setter methods
- (void)setIsEditing:(BOOL)isEditing{
    if (_isEditing != isEditing ) {
        _isEditing = isEditing;
        if (_isEditing) { //当为编辑状态时，flipper禁用
            [[DataEnvironment sharedDataEnvironment].mainViewController setSlideEnabled:NO];
        } else { //恢复flipperalce
            [[DataEnvironment sharedDataEnvironment].mainViewController setSlideEnabled:YES];
        }
    }
}
- (void)setCurrentPage:(NSInteger)currentPage{
    _currentPage = currentPage;
    
    self.pageControl.currentPage = _currentPage;
    if (self.totalPage<=1) {
        self.pageControl.hidden = YES;
    }else{
        self.pageControl.hidden = NO;
    }
}

@end
